from al_earth.main.plugins import GenericEventLoader, Item
from dateutil import rrule
import glob
from os.path import getmtime, basename

class EventLoader(GenericEventLoader):
    event_type = "FilesAndDir"
    def __init__(self,config):
        GenericEventLoader.__init__(self,config)
        self.recursion=rrule.rrule(rrule.SECONDLY, interval=self.config['interval'])
        try:
            self.cache=self.getData()
        except:
            pass

    def getData(self):
        try:
            out = dict([(f,(f,getmtime(f))) for f in glob.glob(self.config['wildchars'])])
        except:
            self.status = "Errors"
            raise
        else:
            self.status = ""

        return out
    def getItems(self):
        items = self.getData()
            
        if items==self.cache:
            return []
        newKeys = set(items)
        oldKeys = set(self.cache)
        new = [items[k] for k in sorted(newKeys - oldKeys)]
        deleted = [self.cache[k] for k in sorted(oldKeys - newKeys)]
        changed =[(items[k],self.cache[k]) for k in sorted(newKeys & oldKeys) if items[k] != self.cache[k]]
        out=[]
        for f in new:
            out.append(Item("New file %s" % (basename(f[0])),
                             "",
                             self.title,
                             None))
        for f in deleted:
            out.append(Item("Deleted file %s" % (basename(f[0])),
                             "",
                             self.title,
                             None))
        for f in changed:
            out.append(Item("File changed %s" % (basename(f[0][0])),
                             "",
                             self.title,
                             None))
        self.cache=items

        return out
    
